package top.lingkang.fas.admin.web;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Assert;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.MethodType;
import top.lingkang.fas.admin.constant.CacheConstants;
import top.lingkang.fas.admin.param.LoginParam;
import top.lingkang.fas.admin.service.SysUserService;
import top.lingkang.fas.admin.utils.RedissonUtil;
import top.lingkang.fas.common.dto.R;
import top.lingkang.finalvalidated.core.ValidObject;

/**
 * @author lingkang
 * created by 2025/7/20 0:03
 */
@Controller
public class WebController {

    @Inject
    private SysUserService sysUserService;

    @Mapping("/")
    public void index(Context ctx) {
        if (StpUtil.isLogin()) {
            ctx.redirect("/page/index.html");
        } else {
            ctx.redirect("/page/login.html");
        }
    }

    @Mapping(value = "/login", method = MethodType.POST)
    public R login(@ValidObject LoginParam param) {
        Assert.notBlank(param.getId(), "验证码错误");
        Integer answer = RedissonUtil.get(CacheConstants.CAPTCHA_CODE_KEY + param.getId());
        Assert.notNull(answer, "验证码错误");
        Assert.isTrue(answer.intValue() == param.getCode().intValue(), "验证码错误");
        return sysUserService.login(param.getUsername(), param.getPassword());
    }
}
